using System.ComponentModel;
using System.Reflection;

namespace Bean.Infrastructure.Extensions;

public static class EnumExtensions
{
    /// <summary>
    /// 获取枚举值上的Description属性的值
    /// </summary>
    /// <param name="enumValue">枚举值</param>
    /// <returns>返回Description的内容</returns>
    public static string GetDescription(this Enum enumValue)
    {
        var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
        var attribute = fieldInfo?.GetCustomAttribute<DescriptionAttribute>();

        return attribute?.Description ?? enumValue.ToString();
    }


    /// <summary>
    /// 将字符串转换为枚举类型
    /// </summary>
    /// <typeparam name="TEnum">枚举类型</typeparam>
    /// <param name="value">要转换的字符串</param>
    /// <param name="ignoreCase">是否忽略大小写</param>
    /// <returns>转换后的枚举值，如果无法转换则返回默认值</returns>
    public static TEnum ToEnum<TEnum>(this string value, bool ignoreCase = true) where TEnum : struct
    {
        try
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentException("The value cannot be null or empty.", nameof(value));
            }

            if (Enum.TryParse<TEnum>(value, ignoreCase, out var result))
            {
                if (!Enum.IsDefined(typeof(TEnum), result))
                {
                    throw new ArgumentException(
                        $"The value '{value}' is not a valid enum value for enum type '{typeof(TEnum)}'.");
                }

                return result;
            }
        }
        catch (Exception e)
        {
            throw new ArgumentException($"Cannot convert '{value}' to enum type '{typeof(TEnum)}'.");
        }

        return default;
    }
    


}